/**
 * components util
 */

import Vue from 'vue'

/**
 * 清理空值，对象
 * @param children
 * @returns {*[]}
 */
export function filterEmpty (children = []) {
  return children.filter(c => c.tag || (c.text && c.text.trim() !== ''))
}

/**
 * 获取字符串长度，英文字符 长度1，中文字符长度2
 * @param {*} str
 */
export const getStrFullLength = (str = '') =>
  str.split('').reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0)
    if (charCode >= 0 && charCode <= 128) {
      return pre + 1
    }
    return pre + 2
  }, 0)

/**
 * 截取字符串，根据 maxLength 截取后返回
 * @param {*} str
 * @param {*} maxLength
 */
export const cutStrByFullLength = (str = '', maxLength) => {
  let showLength = 0
  return str.split('').reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0)
    if (charCode >= 0 && charCode <= 128) {
      showLength += 1
    } else {
      showLength += 2
    }
    if (showLength <= maxLength) {
      return pre + cur
    }
    return pre
  }, '')
}

/**
 * 表格可伸缩
 */

export const resizeTable = (that,columnsName) => {
  if(!columnsName) columnsName='columns'
  const tabComponent =  {
    header: {
      cell: (h, props, children) => {
        const draggingMap = {};
        that[columnsName].map(col => {
          if (col.width < 50)
            col.width = 50
          const k = col.dataIndex || col.key;
          draggingMap[k] = col.width;
        });
        const draggingState = Vue.observable(draggingMap);
        let thDom = null
        const { key, ...restProps } = props;
        const col = that[columnsName].find(col => {
          const k = col.dataIndex || col.key;
          return k === key;
        })
        if (!col.width) {
          return <th {...restProps}>{children}</th>;
        }
        const onDrag = x => {
          draggingState[key] = 0;
          col.width = Math.max(x, 1);
        }
        const onDragstop = () => {
          draggingState[key] = thDom.getBoundingClientRect().width;
        }
        return (
          <th 
            {...restProps}
            v-ant-ref={r => (thDom = r)}
            v-ant-ref={r => (thDom = r)}
            width={draggingState[key]}
            class="resize-table-th"
          >
            {children}
            <vue-draggable-resizable
              key={col.dataIndex || col.key}
              class="table-draggable-handle"
              w={10}
              x={col.width || draggingState[key]}
              z={1}
              axis="x"
              draggable={true}
              resizable={false}
              onDragging={onDrag}
              onDragstop={onDragstop}
            ></vue-draggable-resizable>
          </th>
        )
      }
    }
  }
  return tabComponent
}
